// src/http/interceptor.ts
import { HttpInterceptor, HttpRequestConfig, HttpResponse } from "./types";

class InterceptorManager {
  private requestInterceptors: HttpInterceptor['request'][] = [];
  private responseInterceptors: HttpInterceptor['response'][] = [];

  use(interceptor: HttpInterceptor): void {
    if (interceptor.request) {
      this.requestInterceptors.push(interceptor.request);
    }
    if (interceptor.response) {
      this.responseInterceptors.push(interceptor.response);
    }
  }

  async applyRequestInterceptors(config: HttpRequestConfig): Promise<HttpRequestConfig> {
    let currentConfig = config;
    for (const interceptor of this.requestInterceptors) {
      currentConfig = await interceptor(currentConfig);
    }
    return currentConfig;
  }

  async applyResponseInterceptors(response: HttpResponse): Promise<HttpResponse> {
    let currentResponse = response;
    for (const interceptor of this.responseInterceptors) {
      currentResponse = await interceptor(currentResponse);
    }
    return currentResponse;
  }
}

export const httpInterceptor = new InterceptorManager();